<template>
  <view>
    <block v-for="(item, i) in goodsList" :key="i">
      <my-goods :goods="item" @click="gotoDetail(item.goods_id)"></my-goods>
    </block>
  </view>
</template>

<script>
  // 注意：有时候，easycom 不生效，可以直接导入需要的组件使用
  import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue"
  export default {
    // 注册需要的组件
    components: { uniNumberBox },
    data() {
      return {
        // 请求参数对象
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10
        },
        // 商品列表
        goodsList: [],
        // 总数量
        total: 0,
        // 是否正在请求数据
        isloading: false
      }
    },
    onLoad(options) {
      // 将查询参数，转存到 queryObj 对象中
      for (let k in options) {
        this.queryObj[k] = options[k]
      }

      this.getGoodsList()
    },
    // 触底事件
    onReachBottom() {
      if (this.isloading) return
      // 判断是否还有下一页
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showError('数据加载完毕！')
      // 页码值 +1
      this.queryObj.pagenum++
      // 请求下一页数据
      this.getGoodsList()
    },
    // 下拉刷新的事件
    onPullDownRefresh() {
      this.queryObj.pagenum = 1
      this.goodsList = []
      this.total = 0
      this.isloading = false

      this.getGoodsList(() => uni.stopPullDownRefresh())
    },
    methods: {
      // 发起请求，获取商品列表数据
      async getGoodsList(cb) {
        this.isloading = true
        const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 无论数据获取成功还是失败，都应该 1. 重置节流阀；2. 调用 cb 回调，关闭下拉刷新效果
        this.isloading = false
        cb && cb()
        if (res.meta.status !== 200) return uni.$showError()
        this.total = res.message.total
        this.goodsList = [...this.goodsList, ...res.message.goods]
      },
      gotoDetail(goods_id) {
        uni.navigateTo({
          url: '/packageGoods/goods_detail/goods_detail?goods_id=' + goods_id
        })
      }
    }
  }
</script>

<style lang="scss">
  .thumb-box {
    display: flex;
    align-items: center;

    image {
      width: 180rpx;
      height: 180rpx;
      margin-left: 5rpx;
    }
  }

  .desc-box {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .price {
      font-size: 16px;
      color: #C00000;
    }
  }
</style>
